import { useEffect, useReducer } from "react";
import TodoAdd from "./components/TodoAdd";
import TodoFooter from "./components/TodoFooter";
import TodoList from "./components/TodoList";
import Thenme from "./components/ThemePartnt";
import ThemeContext from "./context";
import reducer from "./todoReducer";
// 导入todos样式
import "./App.css";

const initialState = [{ id: 1, text: "吃饭", done: false }];

const App = () => {
  //页面初始化读取本地化存储
  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    const initTodos = localStorage.getItem("TDLST") ? JSON.parse(localStorage.getItem("TDLST")) : "";
    if (initTodos) {
      dispatch({ type: "geTlocalStorage", payload: state });
    }
  }, []);
  
  //当todos 数据发生改变后把最新的todos 储存在本地
  useEffect(() => { localStorage.setItem("TDLST", JSON.stringify(state));}, [state]);

  //添加任务
  const todoListAdds = (text) => {dispatch({ type: "todosAdd", payload: text });};

  // 切换任务
  const todoListIsShow = (id) => { dispatch({ type: "todoIsShow", payload: id });};

  // 删除任务
  const todoListRemoveId = (id) => { dispatch({ type: "todoRemove", payload: id });};

  return (
    <section className="todoapp">
      <TodoAdd todoListAdd={todoListAdds} />
      <ThemeContext.Provider
        value={{
          todos: state,
          todoListIs: todoListIsShow,
          todoListRemove: todoListRemoveId,
        }}
      >
        <Thenme />
      </ThemeContext.Provider>
      <TodoFooter />
    </section>
  );
};

export default App;
